#include "Gsys.h"

COsfResManage::COsfResManage()
{
	ClearData();
}

COsfResManage::~COsfResManage()
{
}

COsfResManage COsfResManage::s_instance;
COsfResManage* COsfResManage::Instance()
{
	return &s_instance;
}

	
LPVOID COsfResManage::ResGetAddressByLoad(HANDLE hRes, DWORD dwDataID, HRESULT *pResult)
{
	m_ResUsingNum[dwDataID].IsUsing = 1;

	if((INT)m_ResUsingNum[dwDataID].UsingNum+1 >= C_SPR_RES_USE_MAX)
	{
		PrintfString("dwDataID:%d uing too much ", dwDataID) ;
	}
	
	m_ResUsingNum[dwDataID].UsingNum++;
	
	return RES_GetAddressByLoad(hRes, dwDataID, DIS_SCHEDULER, pResult) ;
}

LPVOID COsfResManage::ResGetAddress(HANDLE hRes, DWORD dwDataID, HRESULT *pResult)
{
	if(m_ResUsingNum[dwDataID].IsUsing )
	{
		return RES_GetAddress(hRes, dwDataID, pResult) ;
	}

	return ResGetAddressByLoad( hRes, dwDataID, pResult) ;
}

void COsfResManage::ResReleaseData(HANDLE hRes, DWORD dwDataID )
{	
	//printf(" dwDataID:%x \n ", dwDataID) ;
	if(m_ResUsingNum[dwDataID].IsUsing)
	{
		if(m_ResUsingNum[dwDataID].UsingNum <= 1)
		{
			m_ResUsingNum[dwDataID].IsUsing = 0 ;
			m_ResUsingNum[dwDataID].UsingNum = 0;
			
			//printf(" released  \n") ;
			HRESULT Result = RES_ReleaseData(hRes, dwDataID) ;
			if(Result != 0)
			{
				PrintfString("RES_ReleaseData error ") ;
			}
		}
		else
		{
			m_ResUsingNum[dwDataID].UsingNum--;
		}
	}
}

void COsfResManage::ResReleaseAllData(	HANDLE hRes)
{
	if(hRes == INVALID_HANDLE_VALUE)
	{
		HRESULT Result = RES_ReleaseAllData(hRes);
		if(Result != 0)
		{
			PrintfString("RES_ReleaseAllData error") ;
		}
	}
}

void COsfResManage::ReleaseAllData()
{
	for(int iCnt= 0; iCnt< C_SPR_RES_MAX; ++iCnt)
	{
		if(m_ResUsingNum[iCnt].IsUsing)
		{
			RES_ReleaseData(CGmMemAlloc::GetRes(), iCnt) ;
		}
	}
	
	ClearData();
}

void COsfResManage::ClearData()
{
	for(INT iCnt = 0; iCnt < C_SPR_RES_MAX; ++iCnt)
	{
		m_ResUsingNum[iCnt].IsUsing = 0;
		m_ResUsingNum[iCnt].UsingNum = 0;
	}
}


void COsfResManage::GetDataInfo()
{
	INT iCount = 0;
	for(int iCnt= 0; iCnt< C_SPR_RES_MAX; ++iCnt)
	{
		if(m_ResUsingNum[iCnt].IsUsing)
		{
			printf("Spr: %x, num:%d \n", iCnt, m_ResUsingNum[iCnt].UsingNum);
			++iCount;
		}
	}

	PrintfString(" res sprite :%d ", iCount) ;
}

